<template>
  <div class="form-sparepart">
    <div class="btn-group">
      <!-- start 个人库添加按钮 -->
      <el-button
        class="add-sparepart-btn"
        type="text"
        size="medium"
        v-if="!isTaskCloudWarehousePerson"
        @click="openAddMaterialDialog('personalLibrary')"
      >{{$t('common.form.tip.materialReturn.tips1')}}</el-button>
      <!-- end 个人库添加按钮 -->

      <!-- start 从仓库添加按钮 -->
      <el-button
        type="text"
        size="medium"
        @click="openAddMaterialDialog('warehouse')"
      >{{$t('common.form.tip.materialReturn.tips2')}}</el-button>
      <!-- end 从仓库添加按钮 -->
    </div>
    
    <!-- start 物料列表 -->
    <el-table
      v-if="tableValue.length > 0"
      header-row-class-name="base-table-header-v3"
      row-class-name="base-table-row-v3"
      :data="tableValue"
      max-height="250"
      border>
      
      <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
      
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.field}_${index}_${uuid()}`"
        :label="column.label"
        :prop="column.field"
        show-overflow-tooltip
        :min-width="column.minWidth || '108px'"
        :fixed="column.fixed"
      >
        <template slot-scope="scope">
          <!-- start 返还仓库 -->
          <template v-if="column.field === 'warehouseName'">
            {{ scope.row.warehouseId && scope.row.warehouseName }}
          </template>
          <!-- end 返还仓库 -->
          
          <!-- start 返还仓位 -->
          <template v-else-if="column.field === 'positionName'">
            {{ scope.row.positionId && scope.row.positionName }}
          </template>
          <!-- end 返还仓位 -->

          <!-- start 物料编号 -->
          <template v-else-if="column.field === 'sn'">
            {{ scope.row.sn || scope.row.materialSn }}
          </template>
          <!-- end 返还仓位 -->

          <!-- start 查看SN -->
          <!-- <template v-else-if="column.field === 'SN'">
            <el-button v-if="scope.row.snManage === '是'" class="text-danger" type="text" size="mini" @click="openSnDialog('edit', scope.row, scope.$index)">查看</el-button>
          </template> -->
          <!-- end 查看SN -->
          <template v-else-if="column.field === 'salePrice'">
            {{ scope.row | fmt_salePrice_currency }} 
          </template>
          <!-- start 操作 -->
          <template v-else-if="column.field === 'action'">
            <el-button class="text-danger" type="text" size="mini" @click="deleteItem(scope)">
              {{$t('common.base.delete')}}
            </el-button>
          </template>
          <!-- end 操作 -->

          <!-- 富文本 -->
          <template v-else-if="column.setting && column.setting.originalFormType === 'richtext'">
            <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
              <span v-if="scope.row && scope.row.attribute && scope.row.attribute[column.fieldName]">{{$t('common.base.view')}}</span>
            </div>
          </template>
          
          <!-- start 默认显示 -->
          <template v-else>
            {{ $formatFormField(column, scope.row) }}
          </template>
          <!-- end 默认显示 -->
          
        </template>
      </el-table-column>
    </el-table>
    <!-- end 物料列表 -->

    <!-- start sn弹窗 -->
    <material-sn-dialog 
      ref="materialSnDialog" 
      :data="tableValue"
      @changeSn="changeSn"
    />
    <!-- end sn弹窗 -->

    <!-- start 添加物料 -->
    <material-apply-dialog 
      ref="materialApplyDialog" 
      :field="field"
      @input="confirmApply" 
    />
    <!-- end 添加物料 -->

    <!-- 富文本弹窗 -->
    <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform'

/* components */
import MaterialSnDialog from './components/MaterialSnDialog';
import MaterialApplyDialog from './components/MaterialApplyDialog';
import MaterialTable from './components/MaterialTable.vue';
/* mixin */
import FormMixin from '@src/component/form/mixin/form';
import i18n from '@src/locales'

/* util */
import _ from 'lodash';
import { getRootWindow } from '@src/util/dom'
export default {
  name: 'form-materialreturn',
  mixins: [FormMixin],
  inject: ['initData'],
  props: {
    field: {
      type: Object,
      default: () => ({})
    },
    value: {
      type: Array,
      default: () => ([])
    },
  },
  data() {
    return {
      materialTableData:[],
      isOpenData,
      visible: false,
      warehouseList: [],
      warehouseId: {},
      warrantyStatusMap: {
        0: i18n.t('common.base.warranty'),
        1: i18n.t('common.base.surrender')
      }
      
    }
  },
  computed: {
    // 是否开启个人库灰度
    isTaskCloudWarehousePerson() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskCloudWarehousePerson || false
    },
    //  是否需要填写被替换物料
    showReplacedMaterialCheck() {
      let { replacedMaterialCheck } = this.initData?.materialInfo || {}
      return replacedMaterialCheck || false
    },
    tableValue(){
      return this.value || []
    },
    /** 
    * @description 质保状态
    */
    warrantyStatus() {
      let { warrantyStatus } = this.initData?.materialInfo || {}
      warrantyStatus = warrantyStatus === 'IN' ? 0 : 1
      return this.warrantyStatusMap[warrantyStatus] || ''
    },
    /**
    * @description 是否显示质保字段
    */
    showWarrantyStatus() {
      let { showWarrantyStatus } = this.initData?.materialInfo || {}
      return showWarrantyStatus
    },
    // 关联物料字段
    relationMaterialFields() {
      let newFields = (this.field?.setting?.materialFields || []).map(item => {
        return {
          ...item,
          label: item.displayName,
          field: item.fieldName
        }
      })
      return newFields;
    },
    /**
    * @description 回执物料列表项
    */
    columns() {
      // TODO 可能存在判断label的情况
      let columns = [
        ...this.relationMaterialFields,
        {
          label: this.$t('common.form.preview.materialReturn.tableLabel3'),
          field: 'SN',
        },
        {
          label: this.$t('common.form.preview.materialReturn.tableLabel7'),
          field: 'warrantyStatus'
        },
        {
          label: this.$t('common.form.preview.materialReturn.tableLabel8'),
          field: 'warehouseName',
        }, 
        {
          label: this.$t('common.form.preview.materialReturn.tableLabel9'),
          field: 'positionName',
        },
        {
          label: this.$t('common.form.preview.materialReturn.tableLabel10'),
          field: 'number',
          minWidth: '110px',
        },
        {
          label: this.$t('common.base.operation'),
          field: 'action',
          fixed: 'right',
          minWidth: '70px'
        }
      ]
      if(!this.showWarrantyStatus) {
        columns = columns.filter(item => item.field !== 'warrantyStatus')
      }

      // 完成回执-物料返还 是否隐藏终端销售价
      if(!this.serviceProviderShowPrice) {
        columns = columns.filter(item => item.field !== 'salePrice')
      }

      return columns;
    },
  },
  methods: {
    changeSn(data) {
      this.$emit('update', { field: this.field, newValue: data });
    },
    openSnDialog(type, row, index) {
      this.$refs.materialSnDialog.open(type, row, index)
    },
    deleteItem(scope){
      // 当前删除的数据是表格的第几行数据的下标，从零开始。
      const index = scope.$index 
      this.tableValue.splice(index, 1)
      this.$emit('update', { field: this.field, newValue: this.tableValue });
    },
    /**
    * @description 打开物料弹窗
    */
    openAddMaterialDialog(type) {
      const data = JSON.parse(window.localStorage.getItem('materialTableData'))
      this.materialTableData = []
      if(data?.length){
        data.forEach(item =>{
          if(item.replacedMaterial){
            const replacedMaterial = item.replacedMaterial
            let obj = {
              ...item.replacedMaterial,
              id:replacedMaterial.materialId || replacedMaterial.id,
              image:replacedMaterial.image,
              images:replacedMaterial.images,
              isReplaced:replacedMaterial.isReplaced,
              materialId:replacedMaterial.materialId || replacedMaterial.id,
              materialName :replacedMaterial.materialName || replacedMaterial.name,
              name :replacedMaterial.materialName || replacedMaterial.name,
              num: 1,
              materialSn :replacedMaterial.materialSn || replacedMaterial.sn,
              property :replacedMaterial.property || replacedMaterial.materialProperty,
              salePrice :replacedMaterial.salePrice || 0,
              unit :replacedMaterial.unit || replacedMaterial.materialUnit,
              snManage :replacedMaterial.snManage,
              warrantyStatus :replacedMaterial.warrantyStatus || this.warrantyStatus,
              SN:item.replacedMaterialSN,
              replacedMaterialSN:item.replacedMaterialSN,
              number:item.number,
              machine: item.machine,
              // 当前核销对应的物料SN前端自己定义的字段当做核销和返还的标识
              initMaterialSN:item.SN
            }
            this.materialTableData.push(obj)
          }
        })
      }
      let typeMap = {
        title: this.$t('common.form.tip.materialReturn.tips1'),
        type: 'personalLibrary'
      }
      // 仓库
      if(type === 'warehouse') {
        typeMap.title = this.$t('common.form.tip.materialReturn.tips2')
        typeMap.type = 'warehouse'
      }

      this.$refs.materialApplyDialog.open(typeMap)
    },
    confirmApply({ data }) {
      data.forEach(item => {
        // 返还物料没有质保状态就取工单详情的
        item.warrantyStatus = item.warrantyStatus || this.warrantyStatus
        // 如果它不是被替换物料的标识，且也不是SN的物料
        if(!item.isReplaced && item.snManage !== '是'){
          let idx = this.tableValue.findIndex(val => (val.id === item.id || val?.primaryId == item.id) && val.warehouseId === item.warehouseId && val.positionId === item.positionId)
          // 不存在
          if (idx == -1) {
            this.tableValue.push(item)
          } else {
            const newItem = {
              ...this.tableValue[idx],
              ...item,
              number: item.number + this.tableValue[idx].number,
            }
            this.$set(this.tableValue, idx, newItem)
          }
        }else {
          for(let i = 0; i < item.number; i++){
              let obj = {
                ...item,
                number:1
              }
            this.tableValue.push(obj)
          }
        }
      })
      // 修改了传值 对象改为数组
      this.$emit('update', { field: this.field, newValue: this.tableValue });
      this.$refs.materialApplyDialog.close()
    },
    /** 打开富文本弹窗 */
    openRichtextVisible(row, column) {
      const richtextId = row?.attribute?.[column.fieldName] || ''
      this.$refs?.baseViewRichTextRef?.openDialog(richtextId, false, true);
    }
  },
  components: {
    [MaterialSnDialog.name]: MaterialSnDialog,
    [MaterialApplyDialog.name]: MaterialApplyDialog,
    [MaterialTable.name]: MaterialTable
  }
}
</script>

<style lang="scss" scope>
.form-sparepart-modal {
  z-index: 990 !important; // 选择地址被遮盖降低层级
}
.form-item.err :not(.is-success){
  .form-item :not(.err) {
    input, textarea, .base-select-main-content {
      border-color: #e0e1e2 !important;
    }
  }

  .form-item.err {
    input, .base-select-main-content {
      border-color: #f56c6c !important;
    }
  }
}

.form-sparepart{
  text-align: left;

  .btn-group {
    padding: 0 !important;

    .el-button {
      min-width: auto !important;
      padding: 8px 0 0 0;
    }
  }

  .el-table {
    margin: 10px 0;

    .sparepart-number-input {
      width: 99%;
    }

    .el-icon-delete {
      font-size: 16px;
      color: $color-danger;
      font-weight: 700;
    }
  }
}

.sparepart-template-option {
  * {
    margin: 0;
  }
  padding: 10px 0;
  h3 {
    font-size: 14px;
    font-weight: 500;
    line-height: 24px;
  }

  p {
    display: flex;
    justify-content: space-between;
    line-height: 24px;

    & > span {
      width: 25%;
      display: flex;
      justify-content: flex-start;
      font-size: 12px;
      color: #666666;
      padding-right: 10px;

      & > label {
        flex-shrink: 0;
        padding: 0;
        width: 40px !important;
      }
      & > span {
        flex-grow: 1;
        @include text-ellipsis();
      }
    }
  }
  .sparepart-addition-info {
    & > span {
      width: 50%;
      .addition-product-type {
        width: auto !important;
      }
    }
  }
}
.free-sparepart-fee {
  .iconfont {
    color: #FAAD14;
    margin-right: 8px;
  }
}
.goget-box{
  position: relative;
}
.goget{
  position: absolute;
    right: 35px;
    top: 0;
    line-height: 32px;
    cursor: pointer;
    color: $color-primary-light-6;
}
</style>
<style lang="scss" scoped>
.update-sparepart-title {
  margin-left: 20px;
  color: $color-primary-light-6;
}
.update-sparepart-mess {
  margin: 8px 0px 18px 8px;
  color: $color-primary-light-6;
}
</style>
